package org.huang.zhen;

import org.huang.zhen.GameMap;

import java.awt.*;

public class GameMapCanvas extends MagicBlockCanvas {

    private Image mBuffer;
    private int [][]mMap;

    public GameMapCanvas(int x, int y) {
        super();
        setBounds(x,y, BLOCK_PIXEL * GameMap.GAME_MAP_SIZE_COL, BLOCK_PIXEL * GameMap.GAME_MAP_SIZE_ROW);
    }

    public void refresh(int [][]map) {
        mMap = map;
        repaint();
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        drawBackground(g);
        drawLines(g);
    }

    public void update(Graphics g) {
        if (mBuffer == null) {
            mBuffer = createImage(getWidth(), getHeight());
        }
        Graphics2D bufG2D = (Graphics2D)mBuffer.getGraphics();
        drawBackground(bufG2D);
        bufG2D.setColor(Color.PINK);
        for (int i = 0; i < mMap.length; i ++) {
            for (int j = 0; j < mMap[i].length; j ++) {
                if (mMap[i][j] == 1) {
                    bufG2D.drawRect(j* BLOCK_PIXEL, i * BLOCK_PIXEL, BLOCK_PIXEL, BLOCK_PIXEL);
                    bufG2D.fillRect(j * BLOCK_PIXEL, i * BLOCK_PIXEL, BLOCK_PIXEL, BLOCK_PIXEL);
                }
            }
        }
        drawLines(bufG2D);
        g.drawImage(mBuffer, 0 ,0, this);

    }

    private void drawBackground(Graphics g) {
        Graphics2D g2d = (Graphics2D)g;
        g2d.setColor(Color.LIGHT_GRAY);
        g2d.drawRect(GAME_MAP_MARGIN_LEFT, GAME_MAP_MARGIN_TOP, BLOCK_PIXEL * GameMap.GAME_MAP_SIZE_COL, BLOCK_PIXEL *GameMap.GAME_MAP_SIZE_ROW);
        g2d.fillRect(GAME_MAP_MARGIN_LEFT, GAME_MAP_MARGIN_TOP, BLOCK_PIXEL * GameMap.GAME_MAP_SIZE_COL, BLOCK_PIXEL *GameMap.GAME_MAP_SIZE_ROW);
    }

    private void drawLines(Graphics g) {
        Graphics2D g2d = (Graphics2D)g;
        g2d.setColor(Color.white);
        BasicStroke stroke = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 5.0f, new float[]{2,2}, 0);
        g2d.setStroke(stroke);
        for (int i = 1; i < GameMap.GAME_MAP_SIZE_COL; i++) {
            g2d.drawLine(GAME_MAP_MARGIN_LEFT + BLOCK_PIXEL * i, GAME_MAP_MARGIN_TOP, GAME_MAP_MARGIN_LEFT + BLOCK_PIXEL * i, BLOCK_PIXEL * GameMap.GAME_MAP_SIZE_ROW + GAME_MAP_MARGIN_TOP );
        }
        for (int i = 1; i < GameMap.GAME_MAP_SIZE_ROW; i++) {
            g2d.drawLine(GAME_MAP_MARGIN_LEFT, GAME_MAP_MARGIN_TOP + BLOCK_PIXEL * i, GAME_MAP_MARGIN_LEFT + BLOCK_PIXEL * GameMap.GAME_MAP_SIZE_COL, GAME_MAP_MARGIN_TOP + BLOCK_PIXEL * i);
        }
    }



    public int getWidth() {
        return BLOCK_PIXEL * GameMap.GAME_MAP_SIZE_COL;
    }

    public int getHeight() {
        return BLOCK_PIXEL *GameMap.GAME_MAP_SIZE_ROW;
    }
}
